package com.alinesno.cloud.operation.cmdb.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 下载路径  
 * @author WeiXiaoJin
 * @since 2019年3月14日 下午8:55:21
 */
@Controller
@RequestMapping("/manager/")
public class DownloadController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Value("${excel.temp.dir}")
	private String stackFileExport ; // 输出路径  
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@GetMapping("/download")
	public void downloadFile(HttpServletRequest request, String fileName , HttpServletResponse response) {
		
		logger.debug("file name = {}" , fileName);
		
		if (fileName != null) {
			File file = new File(stackFileExport+"/"+fileName);
			
			if (file.exists()) {
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;

				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

}
